import React from 'react';
import { connect } from 'react-redux';
import { Form, Row, Col, DatePicker, Input, Button, Popover, Modal, Icon, message } from 'antd';
import ResizeTable from 'components/resize-table';
import SlideFrame from 'components/slide-frame';
import NewExpense from 'containers/my-account/new-expense';
import DDTransformPage from './didi-personal-transfer';
import './didi-expense.scss';
import DiDiService from './didi-expense.service';
import NewRepayment from './new-repayment';
import moment from 'moment';
import { deepFullCopy, messages } from 'share/common';
import AgentModal from './agent-modal';
const FormItem = Form.Item;
import TransformPage from './to-borrow-or-expense';



// 我的账本-嘀嘀打车消费
class DiDiExpenseList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      searchForm: [{
        id: 'departureTime',
        label: '上车时间',
        component: 'DatePicker',
        initialValue: ''
      }, {
        id: 'actualStartName',
        label: '上车地点',
        component: 'Input',
        initialValue: ''
      }, {
        id: 'finishTime',
        label: '下车时间',
        component: 'DatePicker',
        initialValue: ''
      }, {
        id: 'actualEndName',
        label: '下车地点',
        component: 'Input',
        initialValue: ''
      }],
      columns: [{
        width: '50px',
        title: '序号',
        key: 'order',
        dataIndex: 'order',
        render: (text) => {
          return text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>;
        }
      }, {
        width: '100px',
        title: '支付状态',
        key: 'status',
        dataIndex: 'status',
        render: (status) => {
          return status == '5' ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content='未支付'>未支付</Popover> : <span>已支付</span>;
        }
      }, {
        width: '200px',
        title: '上车时间',
        key: 'departureTime',
        dataIndex: 'departureTime',
        render: (text) => {
          return text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>;
        }
      }, {
        width: '200px',
        title: '上车地点',
        key: 'actualStartName',
        dataIndex: 'actualStartName',
        render: (text) => {
          return text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>;
        }
      }, {
        width: '200px',
        title: '下车时间',
        key: 'finishTime',
        dataIndex: 'finishTime',
        render: (text) => {
          return text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>;
        }
      }, {
        width: '200px',
        title: '下车地点',
        key: 'actualEndName',
        dataIndex: 'actualEndName',
        render: (text) => {
          return text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>;
        }
      }, {
        width: '200px',
        title: '金额',
        key: 'companyRealPay',
        dataIndex: 'companyRealPay',
        render: (text) => {
          return text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>0</span>;
        }
      }],
      data: [],
      loading: false,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        size: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      selectedRowKeys: [], // 被勾选的滴滴打车消费记录的orderId
      didiExpenseInfo: [], // 被勾选的滴滴打车消费记录的信息
      showNewExpensePage: false,
      agendVisible: false,
      agentUser: undefined,
      dataList: [],
      showTransformPage: false, // 是否展示转因私或生成费用选择拆分数据的抽屉（转因私/生成费用）
      showTransformPages: false, //生成费用
      transformType: 2, // 1：生成费用，2：转因私
      showNewRepayPage: false, // 是否展示新建还款单抽屉（转因私）
      allSelectedRecords: [], // 既有拆分数据也有公务卡消费记录
      total: null, // 转因私或生成费用被选中的总金额
      params: {}, // 转因私的接口传参
      resetTransformPage: null, // 重置转因私或生成费用的金额选择页面
      info: {},
      didiMoney: [      // 滴滴用车额度
        {
          key: 'innitBudget',
          label: '滴滴预算额',
        },
        {
          key: 'usedBudget',
          label: '滴滴占用额',
        },
        {
          key: 'reserveBudget',
          label: '滴滴恢复额',
        },
        {
          key: 'remainingBudget',
          label: '滴滴余额',
        },
      ],
      didiMoneyRes: {},   // 接口返回的滴滴额度数据
    };
  }

  componentDidMount() {
    // this.getDiDiList();
    this.getListData();
  }

  getListData = async () => {
    const data = await DiDiService.getProxyPrincipals();
    if (data.status === 200) {
      if (data.data && data.data.length > 0) {
        this.setState({
          agendVisible: true,
          dataList: data.data
        })
      } else {
        this.setState({
          agendVisible: false
        }, () => {
          this.getDiDiList();
        })
      }
    }
    console.log('data', data)
  }

  /**
   * 对筛选表单的上车时间和下车时间进行校验
   * @param {Object} rule
   * @param {*} value
   * @param {Function} callback
   */
  formValidator = (rule, value, callback, type) => {
    const departureTime = this.props.form.getFieldValue('departureTime');
    const finishTime = this.props.form.getFieldValue('finishTime');
    if (['departureTime', 'finishTime'].includes(type)) {
      if (departureTime && finishTime) {
        if (departureTime.isSameOrAfter(finishTime)) {
          callback('上车时间应早于下车时间');
        }
      }
    }
    callback();
  }

  /**
   * 返回要渲染的筛选表单组件
   */
  renderSearchFormItem = () => {
    const { getFieldDecorator } = this.props.form;
    const labelObj = {
      departureTime: '上车时间',
      finishTime: '下车时间',
      actualStartName: '上车地点',
      actualEndName: '下车地点'
    };
    const formItems = this.state.searchForm.map((item) => {
      let formItem = null;
      if (['departureTime', 'finishTime'].includes(item.id)) {
        formItem = <DatePicker
          style={{ width: '100%' }}
          format={'YYYY-MM-DD'}
          placeholder={'请选择'}
        />;
      } else if (['actualStartName', 'actualEndName'].includes(item.id)) {
        formItem = <Input placeholder={'请输入'} onChange={this.onChange} />;
      }
      return (
        <Col span={6}>
          <FormItem
            style={{ marginBottom: '15px' }}
            key={item.id}
            label={labelObj[item.id]}
          >
            {
              getFieldDecorator(item.id, {
                rules: [{
                  validator:
                    (rule, value, callback) => this.formValidator(rule, value, callback, item.id)
                }]
              })(formItem)
            }
          </FormItem>
        </Col>
      );
    });
    return formItems;
  }

  /**
   * 根据用户输入的筛选条件进行滴滴消费记录筛选
   * @param {String} type 重置或搜索 重置：reset 搜索：search
   */
  filterData = (type) => {
    const pagination = deepFullCopy(this.state.pagination);
    pagination.current = 1;
    pagination.page = 0;
    if (type === 'reset') {
      this.props.form.resetFields();
    }
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          loading: true,
          pagination
        }, () => {
          this.getDiDiList();
        });
      }
    });
  }

  /**
   * 获取滴滴打车消费记录
   */
  getDiDiList = async () => {
    const searchCondition = this.props.form.getFieldsValue();
    if (searchCondition.departureTime) {
      searchCondition.departureTime = searchCondition.departureTime.format('YYYY-MM-DD');
    }
    if (searchCondition.finishTime) {
      searchCondition.finishTime = searchCondition.finishTime.format('YYYY-MM-DD');
    }
    if (this.state.agentUser) {
      searchCondition.userOID = this.state.agentUser.userOID
    }
    const didiRes = await DiDiService.getDiDiList(this.state.pagination, searchCondition);
    if (didiRes.status === 200) {
      if (didiRes.data && didiRes.data.length === 0) { // 如果非首页获取到的数据为空数组，那就获取前一页的数据
        if (this.state.pagination.page > 0) {
          const tempPagination = deepFullCopy(this.state.pagination);
          tempPagination.page = this.state.pagination.page - 1;
          tempPagination.current = this.state.pagination.current - 1;
          this.setState({
            pagination: tempPagination
          }, () => {
            this.getDiDiList();
          });
          return false;
        }
      }
      const paginationTemp = Object.assign({}, this.state.pagination, { total: Number(didiRes.headers['x-total-count'] || '0') });
      const result = didiRes.data.map((didi, index) => {
        const tempDiDi = didi;
        tempDiDi.order = index + 1;
        tempDiDi.departureTime = didi.departureTime ? moment(didi.departureTime).format('YYYY-MM-DD HH:mm:ss') : null;
        tempDiDi.finishTime = didi.finishTime ? moment(didi.finishTime).format('YYYY-MM-DD HH:mm:ss') : null;
        return tempDiDi;
      });
      this.setState({
        data: result,
        pagination: paginationTemp,
        loading: false
      });
    }

    const didiMoneyRes = await DiDiService.getDiDiMoneyList();
    if (didiMoneyRes.status === 200 && didiMoneyRes.data){
      this.setState({didiMoneyRes :didiMoneyRes.data})
    }
    
  }

  /**
   * 分页触发事件
   * @param {Object} pagination
   */
  onChangePage = (pagination) => {
    const paginationTemp = Object.assign({}, { ...this.state.pagination }, {
      current: pagination.current,
      page: pagination.current - 1,
      pageSize: pagination.pageSize,
      size: pagination.pageSize
    });
    this.setState({
      pagination: paginationTemp,
      loading: true
    }, () => {
      this.getDiDiList();
    });
  }

  /**
   * 点击“生成费用”按钮触发
   */
  toExpense = async () => {
    // const { selectedRowKeys, didiExpenseInfo } = this.state;
    // if (selectedRowKeys.length === 0) {
    //   message.error('请先勾选滴滴打车消费记录');
    //   return false;
    // }
    // const didiRes = await DiDiService.getRecordsByIds(selectedRowKeys);
    // if (didiRes.status === 200) {
    //   if ((didiRes.data || []).length !== this.state.selectedRowKeys.length) {
    //     message.error('存在滴滴消费记录获取消费记录详情失败，无法生成费用');
    //     return false;
    //   }
    //   this.setState({
    //     didiExpenseInfo: didiRes.data || [],
    //     showNewExpensePage: true
    //   });
    // }
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length === 0) {
      message.error(messages('mcd.myAccount.publicServiceCardBankBill.unselectedErrmsg'))
      return false;
    }
    const res = await DiDiService.getRecordsByIds(selectedRowKeys);
    const obj = {};
    let namelist = [];
    res.data.map((record) => {
      namelist.push(record.acpName)
      obj[record.id] = record.oriCurAmt;
    });
    let nameTrue = false;
    let trueList = Array.from(new Set(namelist));
    if (trueList.length === 1) {
      nameTrue = true;
    }
   
    if (nameTrue) {
      if (res.status === 200) {
        this.setState({
          selectedRows: res.data,
          selectedOriCurAmt: obj
        }, () => {
          this.setState({
            transformType: 1,
            showTransformPages: true
          });
        });
      }
    } else {
      message.error(messages('mcd.myAccount.publicServiceCardBankBill.refuseDifferenceBusiness'));
    }
  }

  /**
   * 关闭生成费用抽屉触发
   */
  handleOnNewExpenseClose = () => {
    this.setState({
      showNewExpensePage: false
    }, () => {
      this.getDiDiList();
    });
  }

   /**
   * 关闭生成费用抽屉触发
   */
   handleClose = () => {
    this.setState({
      showTransformPages: false
    });
  }

  /**
   * 当费用生成成功之后
   * 1、需要重新获取滴滴打车消费的数据
   * 2、需要清空被选中的滴滴消费记录
   */
  resetDiDiPage = () => {
    this.setState({
      selectedRowKeys: [],
      didiExpenseInfo: [],
      showNewExpensePage: false
    }, () => {
      this.getDiDiList();
    });
  }

  changeAgentData = (isAgent, user) => {
    if (isAgent) {
      this.setState({
        agentUser: user,
        agendVisible: false
      }, () => {
        this.getDiDiList();
      })
    } else {
      this.setState({ agendVisible: false }, () => {
        this.getDiDiList();
      })
    }
  }

  /**
  * 点击转因私按钮触发
  * 1、总消费金额相加小于等于0的数据记录不能转因私
  * 2、选中的币种需要相同
  */
  handleOnToBorrow = async () => {
    const { selectedRowKeys, didiExpenseInfo } = this.state;
    if (selectedRowKeys.length === 0) {
      message.error('请先勾选滴滴打车消费记录');
      return false;
    }
    const res = await DiDiService.getRecordsByIds(selectedRowKeys);
    if (res.status === 200) {
      if ((res.data || []).length !== selectedRowKeys.length) {
        message.error('存在滴滴消费记录获取消费记录详情失败，无法转因私');
        return false;
      }
      this.setState({
        didiExpenseInfo: res.data,
      }, () => {
        this.setState({
          showTransformPage: true
        });
      });
    }
  }
  /**
  * 收起右侧操作面板
  * @param {String} type 
  */
  handleOnHideSlide = (type) => {
    switch (type) {
      case 'transform':
        this.setState({
          showTransformPage: false,
          showTransformPages: false,
        });
        break;
      default:
        break;
    }
  }
  /**
 * 转因私或生成费用的拆分数据选择抽屉给公务卡消费列表页传用户勾选的要转因私的拆分记录
 * @param {Object} info 被选中的拆分数据，没有公务卡消费记录
 * @param {*} total 被选中的拆分数据的总金额
 * @param {*} params 转因私的接口需要的参数
 * @param {*} allSelectedRecords 被选中的拆分数据包括公务卡消费记录
 */
  setInfo = (info, total, params, allSelectedRecords, handleOnReset) => {
    if (this.state.transformType === 2) {
      this.setState({
        info,
        total,
        params,
        allSelectedRecords,
        showTransformPage: false,
        showNewRepayPage: true,
        resetTransformPage: handleOnReset
      }, () => {
        handleOnReset();
      });
    }
  }
  /**
    * 返回右侧转因私抽屉
    */
  renderTransformPage = () => {
    const { didiExpenseInfo } = this.state;
    const records = didiExpenseInfo.map((row) => {
      row.showDetails = false;
      return row;
    });
    return (
      <DDTransformPage
        showTransformPage={this.state.showTransformPage}
        transformType={this.state.transformType}
        selectedRowKeys={this.state.selectedRowKeys}
        hideSlide={this.handleOnHideSlide}
        records={records}
        setInfo={this.setInfo}
      />
    );
  }

  /**
    * 返回右侧生成费用
    */
  renderTransformPages = () => {
    
    const { selectedRows, agentUser } = this.state;
    console.log(agentUser,'agentUser');
    // const records = selectedRows.map((row) => {
    //   row.showDetails = false;
    //   return row;
    // });
    const records = selectedRows
    console.log(records, 'records1');
    console.log(selectedRows, 'selectedRows');
    
    return (
      <TransformPage
        showTransformPage={this.state.showTransformPages}
        transformType={this.state.transformType}
        // selectedRowKeys={selectedRowKeys}
        hideSlide={this.handleOnHideSlide}
        records={records}
        setInfo={this.setInfo}
        params={{
          didiExpenseInfo: records,
          // didiOrderKeys: selectedRowKeys,
          type: 2,
          isDiDi:true,
          readOnly: false,
          businessCardEnabled: true,
          getDiDiList:this.getDiDiList,
          nowExpense: null,
          expenseSource: 'expenseType',
          slideFrameShowFlag: this.state.showNewExpensePage,
          user: this.props.user,
          hasInit: false,
          receiptOperateScene: 2,
          isCopy: false,
          resetDiDiPage: this.resetDiDiPage,
          agentName: agentUser && agentUser.fullName,
          agentOid: agentUser && agentUser.userOID,
          showNewExpensePage: this.state.showNewExpensePage,
          handleOnNewExpenseClose: this.handleOnNewExpenseClose,
          handleClose: this.handleClose,
          closeFun: this.handleOnNewRepaymentClose,
          transForm: this.transForm,

        }}
      />
    );
  }
  /**
  * 新建还款单抽屉关闭
  */
  handleOnNewRepaymentClose = () => {
    this.setState({
      showNewRepayPage: false,
      showTransformPage: false,
      showTransformPages: false,
    }, () => {
      this.getDiDiList();
    });
  }

   /**
  * 生成费用跳转类型页面
  */
   transForm = () => {
    this.setState({
      showNewExpensePage: true,
      showTransformPages: false
    });
  }

  /**
   * 新建还款单提交成功之后触发
   */
  handleOnNewRepaymentSubmit = () => {
    this.state.resetTransformPage && this.state.resetTransformPage();
    this.setState({
      showNewRepayPage: false,
      loading: true,
      selectedRowKeys: [], // 被选中的行的所有id
      // selectedOriCurAmt: {}, // 被选中的行的总消费额数据
      selectedRows: [], // 被选中的行的所有数据
    }, () => {
      this.getDiDiList();
    });
  }

  // 渲染滴滴额度信息
  renderDiDiMoneyField = () => {
    const { didiMoney, didiMoneyRes } = this.state;
    const arr = [];
    didiMoney.map((item, index) => {
      arr.push(
        <div className="info-item f-left" key={index}>
          <div className="info-item-title">{item.label}</div>
          <div className="info-item-text">
            <span>{didiMoneyRes[item.key]}</span>
          </div>
        </div>
      )
    })
    return arr;
  }

  render() {
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: async (selectedRowKeys) => {

        this.setState({
          selectedRowKeys,
          selectedNum: selectedRowKeys.length
        });
      },
      getCheckboxProps: record => ({
        disabled: !['2','3','4','7'].includes(`${record.status}`),
        name: record.name,
      }),
    };
    const { agendVisible, agentUser } = this.state;
    return (
      <div className={'didiExpensePage'}>
        <div className={'pageTitle'}>滴滴打车消费</div>
        <Form>
          <Row gutter={24}>
            {this.renderSearchFormItem()}
          </Row>
          <Row style={{ marginBottom: '19px' }} gutter={24}>
            <Col span={6}>
              <Button
                onClick={() => this.filterData('search')}
                style={{ marginRight: '5px' }}
                type={'primary'}
                htmlType={'submit'}
              >
                搜索
              </Button>
              <Button
                onClick={() => this.filterData('reset')}
                htmlType={'submit'}
              >
                重置
              </Button>
            </Col>
          </Row>
          <Row style={{ marginBottom: '15px' }} gutter={24}>
            <Col span={10}>
              <Button type={'primary'} style={{ marginRight: '8px' }} onClick={() => this.toExpense()}>生成费用</Button>
              <Button type={'primary'} onClick={() => this.handleOnToBorrow()}>{messages('mcd.myAccount.publicServiceCardBankBill.toBorrow')}</Button>
            </Col>
          </Row>
        </Form>
        <div className="cost-center-extend">
          <div className="cost-center-extend-title">
            {messages('setting.key335'/* 扩展字段*/)}
          </div>
          <div className="info-item-wrap">
            {this.renderDiDiMoneyField()}
            <div className="clear" />
          </div>
        </div>
        <ResizeTable
          rowKey={'id'}
          dataSource={this.state.data}
          loading={this.state.loading}
          pagination={this.state.pagination}
          onChange={this.onChangePage}
          columns={this.state.columns}
          rowSelection={rowSelection}
          size={'middle'}
          bordered
        />
        <SlideFrame
          isShowCloseBtn
          slideFrameKey={'expenseTypeChooseSlideFrameKey'}
          title={'生成费用'}
          width={'800px'}
          show={this.state.showNewExpensePage}
          hasFooter={false}
          content={NewExpense}
          afterClose={this.handleOnNewExpenseClose}
          onClose={() => this.setState({ showNewExpensePage: false })}
          params={{
            didiExpenseInfo: this.state.didiExpenseInfo,
            didiOrderKeys: this.state.selectedRowKeys,
            type: 2,
            isDiDi:true,
            readOnly: false,
            businessCardEnabled: true,
            nowExpense: null,
            expenseSource: 'expenseType',
            slideFrameShowFlag: this.state.showNewExpensePage,
            user: this.props.user,
            hasInit: false,
            receiptOperateScene: 2,
            isCopy: false,
            resetDiDiPage: this.resetDiDiPage,
            agentName: agentUser && agentUser.fullName,
            agentOid: agentUser && agentUser.userOID,
          }}
        />
        {/* 转因私或生成费用选择已拆分数据 */}
        <SlideFrame
          isShowCloseBtn={false}
          slideFrameKey={'toBorrowPageSlideFrameKey'}
          title={messages('mcd.myAccount.publicServiceCardBankBill.toBorrow')}
          width={'800px'}
          show={this.state.showTransformPage}
          content={this.renderTransformPage}
        />
        <SlideFrame
          isShowCloseBtn={false}
          show={this.state.showNewRepayPage}
          title={messages('loan-billing.key42') /* 新建还款 */}
          key={'repaymentLoan'}
          content={NewRepayment}
          params={{
            info: this.state.info,
            params: this.state.params,
            total: this.state.total,
            repayFrame: this.state.showNewRepayPage,
            allSelectedRecords: this.state.allSelectedRecords,
            loanRefund: false,
            closeFun: this.handleOnNewRepaymentClose,
            submitFun: this.handleOnNewRepaymentSubmit,
            agentName: agentUser && agentUser.fullName,
            agentOid: agentUser && agentUser.userOID,
          }}
        />
        {/** 生成费用，新建费用页面 */}
         <SlideFrame
          isShowCloseBtn={false}
          slideFrameKey={'toBorrowPageSlideFrameKey'}
          title={'生成费用'}
          width={'800px'}
          show={this.state.showTransformPages}
          content={this.renderTransformPages}
        />
        <AgentModal
          visible={agendVisible}
          onChange={this.changeAgentData}
          dataList={this.state.dataList}
        />
      </div >
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    enableDepCompany: state.setting.enableDepCompany,
    profile: state.login.profile
  };
}

const WrappedDiDiExpenseList = Form.create()(DiDiExpenseList);

export default connect(mapStateToProps)(WrappedDiDiExpenseList);
